<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class menu_model extends CI_Model {
	//모델 생성자 호출
	function __construct(){
		parent::__construct();
		$this->load->helper('file');
	}
	
	/**
	* create menu to xml file
	*
	* @access	public
	* @return	void
	*/
	function create(){
		
		$this->db->where(array('level > '=>1));
		$this->db->order_by('left');
		$query = $this->db->get('tree');

		$_xml = '';
		$parent_id = null;
		foreach($query->result() as $row){
			
			$this->db->where(array('menu_id'=>$row->id));
			$query1 = $this->db->get('ch_config_contents');
			
			if($query1->num_rows() == 0){ //바로 아래 자식 메뉴 링크 조회
				$this->db->where(array('parent_id'=>$row->id ,'level'=> $row->level+1));
				$this->db->order_by('left');
				$query2 = $this->db->get('tree',1);	
				
				if($query2->num_rows() > 0){
					$row2 = $query2->row_array();
					$this->db->where(array('menu_id'=>$row2['id']));
					$query1 = $this->db->get('ch_config_contents');
				}
				
			}
			
			if($query1->num_rows() > 0){
				
				$row1 = $query1->row_array();
				switch($row1['page_type']){
					case('HTML'):
						$link = '/front/html/id/'.$row1['menu_id'];
					break;
					case('BOARD'):
						$link = '/front/board/list/id/'.$row1['menu_id'];
					break;
					case('GALLERY'):
						$link = '/front/gallery/list/id/'.$row1['menu_id'];
					break;
					case('PLUGIN'):
						$plugin = json_decode($row1['plugin'], true);
						$link = '/'.$plugin['controller'].'/'.$plugin['function'].'/id/'.$row1['menu_id'];
					break;
					default:
						$link = '/front/html/id/'.$row1['menu_id'];
					break;
				}
				//exit;
			}else{
				$link = '/front/waiting';
			}
			
			$title = iconv('utf-8','euc-kr',$row->title);
			if($row->level == 2){ //1depth 
				$parent_id = $row->id;
				
				if($_xml) $_xml .= "</menu>\n";
				$_xml .= "<menu>\n";
				$_xml .= "<menuname>{$title}</menuname>\n";
				$_xml .= "<hyperlink>{$link}</hyperlink>\n";
				$_xml .= "<group>{$parent_id}</group>\n";
			}else if($parent_id == $row->parent_id){
				$_xml .= "\t<menuitem>\n";
				$_xml .= "\t<menuitemname>{$title}</menuitemname>\n";
				$_xml .= "\t<hyperlink>{$link}</hyperlink>\n";
				$_xml .= "<id>{$row->id}</id>\n";
				$_xml .= "\t</menuitem>\n";
			}
			
			
		}
		
		$query->free_result();
	
		$_xml .= "</menu>\n";
		$content = "<?xml version=\"1.0\" encoding=\"euc-kr\"?>\n";
		$content .= "<root>\n";
		$content .= $_xml;
		$content .= "</root>\n";
		
		write_file($this->config->item('ch_path_html').'menu.xml', $content);		
	}
	
	
}
?>